<!-- MarkdownEditor -->
<template>
  <div :class="'markdown-wrapper ' + [isHTML?'disabled':'']">
    <h2 class="title" v-show="isHTML">
      <slot name="title"> </slot>
    </h2>
    <textarea :ref="'editor' + simpleID"></textarea>
  </div>
</template>
<script>
import Simplemde from 'simplemde'
import 'simplemde/dist/simplemde.min.css'
import './markdown.less'
export default {
  name: 'MarkdownEditor',
  props: {
    value: { type: String, default: '' },
    isHTML: { type: Boolean, default: false },
    options: { type: Object, default: () => { return {} } },
    localCache: { type: Boolean, default: true }
  },
  data () {
    /**
     * https://github.com/F-loat/vue-simplemde/blob/HEAD/doc/configuration_zh.md
     */
    return {
      simpleID: Math.round(Math.random() * 1000),
      editor: null, // MarkdownEditor
      configs: {}, // MarkdownEditor options
      callback: null, // callback value
      defaultConfigs: {
        tabSize: 4,
        blockStyles: {
          bold: '**',
          italic: '*'
        },
        insertTexts: {
          horizontalRule: ['', '\n\n-----\n\n'],
          image: ['![](http://', ')'],
          link: ['[', '](http://)'],
          table: ['', '\n\n| Column 1 | Column 2 | Column 3 |\n| -------- | -------- | -------- |\n| Text     | Text      | Text     |\n\n']
        },
        parsingConfig: {
          allowAtxHeaderWithoutSpace: true,
          strikethrough: false,
          underscoresBreakWords: true
        },
        renderingConfig: {
          singleLineBreaks: false,
          codeSyntaxHighlighting: true
        },
        autofocus: true, // 自动聚焦
        autoDownloadFontAwesome: true, // 下载 Font Awesome
        // autosave: { uniqueId: 'VserySimple', enabled: true, delay: 1000 }, // 自动保存
        toolbar: [
          { name: 'bold', action: Simplemde.toggleBold, className: 'fa fa-bold', title: '加粗' },
          { name: 'italic', action: Simplemde.toggleItalic, className: 'fa fa-italic', title: '斜体' },
          { name: 'strikethrough', action: Simplemde.toggleStrikethrough, className: 'fa fa-strikethrough', title: '删除线' },
          { name: 'heading', action: Simplemde.toggleHeadingSmaller, className: 'fa fa-header', title: '标题' },
          { name: 'heading-1', action: Simplemde.toggleHeading1, className: 'fa fa-header fa-header-x fa-header-1', title: '大标题[h1]' },
          { name: 'heading-2', action: Simplemde.toggleHeading2, className: 'fa fa-header fa-header-x fa-header-2', title: '中标题[h2]' },
          { name: 'heading-3', action: Simplemde.toggleHeading3, className: 'fa fa-header fa-header-x fa-header-3', title: '小标题[h3]' },
          { name: 'code', action: Simplemde.toggleCodeBlock, className: 'fa fa-code', title: '代码' },
          { name: 'quote', action: Simplemde.toggleBlockquote, className: 'fa fa-quote-left', title: '引用' },
          { name: 'unordered-list', action: Simplemde.toggleUnorderedList, className: 'fa fa-list-ul', title: '通用列表' },
          { name: 'ordered-list', action: Simplemde.toggleOrderedList, className: 'fa fa-list-ol', title: '编号列表' },
          { name: 'clean-block', action: Simplemde.cleanBlock, className: 'fa fa-eraser fa-clean-block', title: '清除格式' },
          { name: 'link', action: Simplemde.drawLink, className: 'fa fa-link', title: '创建连接' },
          { name: 'image', action: Simplemde.drawImage, className: 'fa fa-picture-o', title: '插入图片' },
          { name: 'table', action: Simplemde.drawTable, className: 'fa fa-table', title: '插入表格' },
          { name: 'horizontal-rule', action: Simplemde.drawHorizontalRule, className: 'fa fa-minus', title: '插入分割线' },
          { name: 'preview', action: Simplemde.togglePreview, className: 'fa fa-eye no-disable', title: '预览' },
          { name: 'side-by-side', action: Simplemde.toggleSideBySide, className: 'fa fa-columns no-disable no-mobile', title: '切换显示' },
          { name: 'fullscreen', action: Simplemde.toggleFullScreen, className: 'fa fa-arrows-alt no-disable no-mobile', title: '切换全屏' },
          { name: 'guide', action: function () { window.open('https://simplemde.com/markdown-guide', '_blank') }, className: 'fa fa-question-circle', title: 'Markdown 指南' }
        ]
      }
    }
  },
  watch: {
    value: function (val) {
      this.editor.togglePreview()
      this.editor.value(val)
      setTimeout(res => { this.editor.togglePreview() }, 300)
    },
    callback: function (val) {
      this.$emit('on-change', val)
    }
  },
  methods: {
    /**
     * init MarkdownEditor
     */
    initEditor () {
      if (this.isHTML) {
        this.editor = new Simplemde({
          status: false,
          toolbar: false,
          tabSize: 4,
          element: this.$refs['editor' + this.simpleID]
        })
        this.editor.value(this.value)
        setTimeout(res => { this.editor.togglePreview() }, 500)
      } else {
        this.configs = Object.assign(this.options, this.defaultConfigs)
        this.editor = new Simplemde(Object.assign(this.configs, {
          element: this.$refs['editor' + this.simpleID]
        }))
        this.addEvents()
        let content = localStorage.markdownContent
        if (content) {
          this.editor.value(content)
        }
      }
    },

    /**
     * add MarkdownEditor Events
     * 事件列表为Codemirror editor的事件，更多事件类型，请参考：
     * https://codemirror.net/doc/manual.html#events
     */
    addEvents () {
      this.editor.codemirror.on('change', () => {
        let value = this.editor.value()
        if (this.localCache) {
          localStorage.markdownContent = value
        }
        this.callback = value
      })
      this.editor.codemirror.on('focus', () => {
        this.callback = this.editor.value()
      })
      this.editor.codemirror.on('blur', () => {
        this.callback = this.editor.value()
      })
    }
  },
  mounted () {
    console.log('test')
    this.initEditor()
  }
}

</script>
